<template>
  <n-layout>
    <n-layout-header :bordered="true">
      <n-space justify="start" align="center">
        <span style="font-size:x-large;font-weight: bold">概况</span>
        <n-icon color="#52c41a" size="24">
          <QuestionCircleFilled/>
        </n-icon>
        <n-statistic :tabular-nums=true>
          <template #prefix>
            <n-text>总量(IMEI):</n-text>
          </template>
          <n-number-animation ref="numberAnimationInstRef" :from="0" :to="totalCounts"/>
        </n-statistic>
      </n-space>
    </n-layout-header>
    <n-layout-content>
      <n-grid cols="1  m:4 l:6 xl:8" responsive="screen">
        <n-grid-item span="1 m:2 l:4 xl:6">
          <!--          <n-card content-style="padding: 0;" :bordered="false">-->
          <div ref="chartRef" class="chart_box"></div>
          <!--          </n-card>-->
          <!--          style="width: 600px;height:480px;"-->
        </n-grid-item>
        <n-grid-item span="1 xl:2">
          <n-space justify="center" align="end" style="padding:10px">
            <span style="font-weight: bold;font-size: large" v-text="TOP20"/>
          </n-space>
          <n-data-table
            id="nearlyTable"
            :remote="true"
            :columns="lastTableColumns"
            :loading="loaderRef"
            :data="dataRef"
            :bordered="false"
            :pagination="false"
            :max-height="400"
            :striped="true"
          />
        </n-grid-item>
      </n-grid>
    </n-layout-content>
  </n-layout>


</template>

<script lang="ts" setup>
import {useRouter} from 'vue-router';
import {onMounted, Ref, ref} from "vue";
import {FormSchema, useForm} from "@/components/Form";
import {useECharts} from "@/hooks/web/useECharts";
import {NumberAnimationInst, useMessage} from "naive-ui";
import {nearlyDay, nearlyDays} from "@/utils/dateUtil";
import {queryTopCountries, queryTotalCounts} from "@/api/statistics/stastistics";
import {utils, writeFileXLSX} from 'xlsx';
// import worldJson from "@/assets/data/map/json/world.json";
import worldJson from "@/assets/data/map/json/ne_10m_admin_0_countries.json";
import {QuestionCircleFilled} from '@vicons/antd';


const router = useRouter();
const message = useMessage();
const queryDate = ref<[string, string]>([nearlyDays(), nearlyDays(1)]);
const chartRef = ref<HTMLDivElement | null>(null);
const {setOptions, getInstance, echarts} = useECharts(chartRef as Ref<HTMLDivElement>);

const dataRef = ref([] as any)
const loaderRef = ref(true)
const totalCounts = ref(0)
const numberAnimationInstRef = ref<NumberAnimationInst | null>(null);

const queryParams = ref({
  project: -1,
  days: 7,
  begin: nearlyDays(7),
  end: nearlyDays(1)
})

// worldJson.features.forEach((feature: any) => {
//   feature.properties&&(feature.propertie.cp = null);
// });
echarts.registerMap('world', worldJson);

const name_map = ref({});
worldJson.features.forEach((feature: any) => {
  const name = feature.properties.name;
  // const full_name = feature.properties.NAME_LONG;
  // const iso = feature.properties.ISO_A2;
  // const code = feature.properties.ISO_N3;
  // name_map.value[iso]= {name, full_name, iso, code, name_zh};
  name_map.value[name] = feature.properties.NAME_ZH;
});

console.log('regions:', name_map);

const lastTableColumns = [
  {
    title: '国家',
    key: 'country',
    align: 'center',
  },
  {
    title: '激活IMEI',
    key: 'count',
    align: 'center',
  },
]

const schemas = ref<FormSchema[]>([
    {
      field: 'project',
      labelMessage: '项目名称',
      component: 'NSelect',
      label: '项目',
      componentProps: {
        placeholder: '请选择项目',
        filterable: true,
        options: [],
        onUpdateValue: (e: any) => {
          queryParams.value.project = e != null ? e : -1;
        },
      },
    },
    {
      field: 'region',
      label: '时间段',
      labelMessage: '时间段',
      component: "NRadioButtonGroup",
      defaultValue: queryParams.value.days,
      componentProps: {
        placeholder: '请选择最近日期',
        filterable: true,
        options: [
          {
            label: '近7天',
            value: 7,
          },
          {
            label: '近30天',
            value: 30,
          }
        ],
        onUpdateValue: (e: any) => {
          queryParams.value.days = e;
          queryDate.value[0] = nearlyDays(e);
          queryDate.value[1] = nearlyDays(1);
          queryParams.value.begin = queryDate.value[0];
          queryParams.value.end = queryDate.value[1];
          schemas.value[2].componentProps!['formattedValue'] = queryDate;
        },
      },
    },
    {
      field: 'dateRange',
      component: 'NDatePicker',
      label: '日期范围',
      componentProps: {
        placeholder: '请选择日期',
        type: 'daterange',
        formattedValue: queryDate,
        // clearable: true,
        onUpdateValue: (e: any, formattedValue: string) => {
          console.log(formattedValue);
          queryParams.value.begin = formattedValue[0];
          queryParams.value.end = formattedValue[1];
        },
        shortcuts:
          {
            '近7天': [new Date(nearlyDays(7)).getTime(), new Date(nearlyDays(1)).getTime()] as const,
            '近30天': [new Date(nearlyDays(30)).getTime(), new Date(nearlyDays(1)).getTime()] as const,
          }
      },
    },
  ])
;

const [register, {}] = useForm({
  gridProps: {
    // xGap: "5",
    // yGap: "8",
    cols: '1  m:1 l:3',
    // collapsed:true,
    collapsedRows: 3,
    // cols: '3'
  },
  // layout: 'horizontal',
  showAdvancedButton: false,
  showResetButton: false,
  labelWidth: 80,
  schemas,
});

setOptions({
  tooltip: {
    trigger: 'item',
    // show: true,
    showDelay: 0,
    transitionDuration: 0.2,
    /*formatter: (params) => {
      const valStr = (params.value + '').split('.')
      const value = valStr[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, `$1,`)
        + '.' + valStr[1];
      return params.seriesName + '<br/>' + params.name + ' : ' + value;
    },*/
    /*  axisPointer: {
        lineStyle: {
          width: 1,
          color: '#019680',
        },
      },*/
  },
  title: {
    text: '地区分布',
    left: 'center',
    textAlign: 'center',
  },
  visualMap: {
    min: 0,
    // max: 1000000,
    text: ['高', '低'],
    realtime: true,
    calculable: true,
    color: ['orangered', 'yellow', 'lightskyblue']
  },

  grid: {left: '5%', right: '5%', top: '15%', bottom: '10%', containLabel: true},

  series: [
    {
      name: '激活数量',
      type: 'map',
      map: 'world',
      top: 60,
      width: '80%',
      aspectScale: 0.75, //长宽比
      itemStyle: {},
      nameMap: name_map.value,
      data: []

    },
  ],
});

function fillDays(days = 7) {
  const titles = [] as any;
  for (let i = days; i > 0; i--) {
    titles.push(nearlyDay(i));
  }
  return titles;
}

onMounted(async () => {
  // const countries = await queryTopCountries({});
  // const projects = [] as any;
  // countries.forEach((e: any) => {
  //   projects.push({label: e['name'], value: e['id']});
  // });
  // schemas.value[0].componentProps!['options'] = projects;
  await getTop20Countries();
});

async function getTop20Countries() {
  const barChar = getInstance();
  barChar?.showLoading();
  loaderRef.value = true;
  const {total} = await queryTotalCounts({});
  totalCounts.value = total;
  const {list} = await queryTopCountries({});
  const country_data = [] as any;
  dataRef.value = list;
  // const titles = fillDays(queryParams.value.days);
  // const count_list: number[] = new Array(queryParams.value.days);
  let max = 200;
  for (const {country, count} of list) {
    // const index = titles.indexOf(date);
    // count_list[index] = counts;
    country_data.push({name: country, value: count});
    if (max<count)max = count;
  }
  console.log(country_data)
  setOptions({
    series: [
      {
        name: '激活数量',
        data: country_data,
      }
    ],
    visualMap: {
      max:max
    }
  }, false);
  barChar?.hideLoading();
  loaderRef.value = false;
  numberAnimationInstRef.value?.play();
}

function handleSubmit() {
  getTop20Countries();
}

function exportTable() {
  const workBook = utils.table_to_book(document.getElementById("nearlyTable"));
  try {
    writeFileXLSX(workBook, "新增用户明细.xlsx");
    message.success("导出成功");
  } catch (e) {
    message.error("导出失败");
  }
}

function chartsSize (container, charts) {
/*  function getStyle(el, name) {
    if (window.getComputedStyle) {
      return window.getComputedStyle(el, null);
    } else {
      return el.currentStyle;
    }
  }*/

  const wi = getStyle(container, 'width').width;
  const hi = getStyle(container, 'height').height*0.8;
  charts.style.width = wi
  charts.style.height = hi
}

window.onresize=function ()
{

  chartsSize(chartRef.value,getInstance());
}
function getStyle(el, name) {
  if (window.getComputedStyle) {
    return window.getComputedStyle(el, null);
  } else {
    return el.currentStyle;
  }
}
</script>

<style lang="less" scoped>

.chart_box{
  width: 98%;
  height: 600px;
  margin: 0 auto;
}

.page-container {
  width: 100%;
  border-radius: 4px;
  padding: 50px 0;
  height: 100vh;

  .text-center {
    h1 {
      color: #666;
      padding: 20px 0;
    }
  }

  img {
    width: 350px;
    margin: 0 auto;
  }
}
</style>
